package com.zysf.library_boot.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zysf.library_boot.entity.Notice;
import com.zysf.library_boot.entity.TypeInfo;
import com.zysf.library_boot.service.NoticeService;
import com.zysf.library_boot.util.Result;
import com.zysf.library_boot.util.UploadFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@RestController
@RequestMapping("/notice")
public class NoticeController {
    @Autowired
    NoticeService noticeService;

    @RequestMapping("/getNotice")
    public Result listNotice(Integer currentPage, Integer pageSize, String topic) {
        Page<Notice> page = new Page<>(currentPage, pageSize);
        QueryWrapper<Notice> queryWrapper = new QueryWrapper<>();
        if (topic != null && !topic.isEmpty()) {
            queryWrapper.like("topic", topic);
        }
        Page<Notice> noticePage = noticeService.page(page, queryWrapper);
        return Result.ok(noticePage);
    }

    @RequestMapping("/noticeTopic")
    public Result noticeTopic(){
        List<Notice> list = noticeService.list();
        return Result.ok(list);
    }

    @RequestMapping("/deleteById")
    public Result deleteById(Integer id){
        boolean g = noticeService.removeById(id);
        return Result.ok(g);
    }

    @RequestMapping("/batchDeleteNotice")
    public Result batchDeleteNotice(@RequestBody List<Integer> ids){
        boolean h = noticeService.removeBatchByIds(ids);
        return Result.ok(h);
    }

    @PostMapping("/addNotice")
    public Result addNotice(@RequestBody Notice notice) {
        boolean saved = noticeService.save(notice);
        if (saved) {
            return Result.ok("添加成功");
        } else {
            return Result.fail("添加失败");
        }
    }

    @GetMapping("/getNoticeById")
    public Result getNoticeById(Integer id) {
        Notice notice = noticeService.getById(id);
        return Result.ok(notice);
    }

    @RequestMapping("/upload")
    public Result upload(MultipartFile file){
        if (file!=null){
            String fileUrl = UploadFile.fileUrl(file);
            return Result.ok(fileUrl);
        }else {
            return Result.fail("文件上传失败");
        }
    }
}
